package pl.edu.agh.student.todo;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Logger;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

import pl.edu.agh.student.todo.dao.Dao;

@SuppressWarnings("serial")
public class ServletCreateTodo extends HttpServlet {
	private static final Logger log = Logger.getLogger(ServletCreateTodo.class.getName());
	
	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		log.info("Creating new todo ");
		User user = (User) req.getAttribute("user");
		if (user == null) {
			UserService userService = UserServiceFactory.getUserService();
			user = userService.getCurrentUser();
		}

		String summary = checkNull(req.getParameter("summary"));
		String longDescription = checkNull(req.getParameter("description"));
		String url = checkNull(req.getParameter("url"));
		String date = checkNull(req.getParameter("date"));
		date = "2012-01-05 17:00 CET";
		
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm Z");

		log.info("USERID: "+user.getUserId());
		try {
			df.parse(date);
			Dao.INSTANCE.add(user.getEmail(), summary, longDescription, url, df.parse(date));
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			log.warning(e.getMessage());
		}

		resp.sendRedirect("/TodoApplication.jsp");
	}

	private String checkNull(String s) {
		if (s == null) {
			return "";
		}
		return s;
	}
}